package com.aizu.controller;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aizu.common.Constant;
import com.aizu.entity.User;
import com.aizu.service.ERentService;
import com.aizu.service.MasterService;
import com.aizu.service.RenterService;
import com.isp.jdbc.model.Pager;
import com.isp.utils.JsonUtil;

@Deprecated
//@Controller
@RequestMapping(value = Constant.PATH_MASTER)
public class MasterController extends CommonController {

	private Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private MasterService masterService;
	@Autowired
	private RenterService renterService;
	@Autowired
	private ERentService eRentService;

	@RequestMapping(value = "/{page}.html")
	public String index(@PathVariable("page") String page, HttpServletRequest request) {
		// 编辑床位
		if ("bedEdit".equals(page)) {
			String communityId = request.getParameter("communityId");
			String roomId = request.getParameter("roomId");

			String communityName = (String) getCommunityValue(communityId, "name");// 小区名
			String deptId = getCommunityValue(communityId, "dept_id") + "";
			String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
			String address = "";// 房间地址
			String roomName = "";// 房间名

			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", roomId);
			try {
				Map<String, Object> room = masterService.findRoom(condition);
				address = departmentName + " " + communityName + " " + (String) room.get("building") + "栋 "
						+ (String) room.get("unit") + "单元";
				roomName = (String) room.get("room_num");
			} catch (Exception e) {
				e.printStackTrace();
			}

			request.setAttribute("address", address);
			request.setAttribute("roomName", roomName);
		}

		return Constant.PATH_MASTER + page;
	}

	/**
	 * 生成4位随机码<br />
	 * 验证手机号是否已存在，存在则不发验证码
	 */
	@Override
	@RequestMapping(value = "/getCode.htm")
	@ResponseBody
	protected String getCode(String phone, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		if (StringUtils.isBlank(phone)) {
			log.debug("手机号不能为空");
			this.toJson(response, "手机号不能为空");
			return null;
		}
		try {
			User user = this.masterService.loadUser(map);
			if (null == user) {
				log.debug("手机号没有本系统内登记，不能发验证码。phone:" + phone);
				this.toJson(response, "手机号还没登记，无法发送验证码");
				return null;
			} else if (null != user && StringUtils.isNotBlank(user.getFromUserName())) {
				log.debug("手机号已被绑定，请先解绑或输入其它手机号");
				this.toJson(response, "手机号已被绑定，请先解绑或输入其它手机号");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.getCode(phone, request, response);
	}

	@RequestMapping(value = "/register.htm")
	public String register(HttpServletRequest request, HttpServletResponse response) {
		String fromUserName = getFromUserName(request);
		String code = request.getParameter("code");
		if (!BooleanUtils.toBoolean(validateCode(code, true, request))) {
			// 验证不通过
			return redirect(Constant.PATH_MASTER + "register.html", request);
		}

		String phone = request.getParameter("phone");
		log.debug("phone: " + phone + ", code: " + code);

		User master = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);

		try {
			master = this.masterService.loadUser(map);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		if (null == master) {
			// map.put("name", "test");
			// map.put("create_date", new Date());
			// map.put("mod_date", new Date());
			// map.put("create_user", 1);
			// map.put("wx_userid", fromUserName);
			//
			// try {
			// master = masterService.saveUser(map);
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			log.info("此手机号码还没有推送到本系统");
			alert("此手机号码还没有推送到本系统", request);
		} else if (StringUtils.isNotBlank(fromUserName)) {
			master.setFromUserName(fromUserName);
			try {
				Map<String, Object> postParam = new HashMap<String, Object>();
				postParam.put("phone", phone);// 手机号码MD5加密
				postParam.put("wxNum", fromUserName);// 微信号码
				Map<String, String> wxDRegister = this.eRentService.wxDRegister(postParam);
				if ("0".equals(wxDRegister.get("flag"))) {
					masterService.updateUser(master);
				} else {
					log.info("接口注册失败，本地不进行注册。  phone: " + phone + ", wxNum: " + fromUserName);
					this.alert(wxDRegister.get("msg"), request);
					master = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.alert("注册失败", request);
				master = null;
			}
		}

		if (null != master) {
			request.getSession().setAttribute(MASTER, master);
			return redirect(Constant.PATH_MASTER + "communityList.htm", request);
		}

		return redirect(Constant.PATH_MASTER + "register.html", request);
	}

	@RequestMapping(value = "/login.htm")
	public String login(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(MASTER);// 清除登陆用户信息
		model.remove(MASTER);

		String phone = request.getParameter("phone");
		String fromUserName = getFromUserName(request);
		log.info("phone: " + phone + ", fromUserName: " + fromUserName);
		if (StringUtils.isBlank(phone) && StringUtils.isNotBlank(fromUserName)) {
			// 微信登陆
			try {
				phone = this.masterService.findPhone(fromUserName);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (StringUtils.isBlank(phone)) {
			// 到注册页面
			log.info("没关联，跳转到注册页面");
			return redirect(Constant.PATH_MASTER + "register.html", request);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		try {
			User user = this.masterService.loadUser(map);
			if (null != user) {
				if (StringUtils.isBlank(user.getFromUserName())) {
					// 到注册页面
					log.info("没关联，跳转到注册页面");
					return redirect(Constant.PATH_MASTER + "register.html", request);
				}
				user.setFromUserName(fromUserName);
				// model.addAttribute(MASTER, user);
				request.getSession().setAttribute(MASTER, user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return redirect(Constant.PATH_MASTER + "communityList.htm", request);
	}

	@RequestMapping(value = "/communityList.htm")
	public String communityList(@ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		// log.debug("masterId: " + masterId);
		List<Map<String, Object>> myCommunity = null;
		try {
			myCommunity = this.masterService.findMyCommunity(master.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("communitys", myCommunity);
		return Constant.PATH_MASTER + "communityList";
	}

	@RequestMapping(value = "/{communityId}/communityEdit.htm")
	public String communityEdit(@PathVariable("communityId") String communityId, @ModelAttribute(MASTER) User master,
			HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String longitude = request.getParameter("longitude");
		String latitude = request.getParameter("latitude");
		String dept_id = request.getParameter("dept_id");
		String address = request.getParameter("address");
		String remark = request.getParameter("remark");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", name);
		map.put("longitude", longitude);
		map.put("latitude", latitude);
		map.put("dept_id", dept_id);
		map.put("address", address);
		map.put("remark", remark);
		try {
			this.masterService.saveCommunity(map, master.getUserId() + "");

			// 重新加载全局小区
			List<Map<String, Object>> communityList = masterService.findCommunity();
			servletContext.setAttribute(Constant.COMMUNITY_LIST, communityList);
			servletContext.setAttribute(Constant.COMMUNITY_MAP, list2Map(communityList));
			servletContext.setAttribute(Constant.COMMUNITY_LIST_JSON, JsonUtil.toJson(communityList));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return redirect(Constant.PATH_MASTER + "communityList.htm", request);
	}

	@RequestMapping(value = "/{communityId}/roomList.htm")
	public String roomList(@PathVariable("communityId") String communityId, @ModelAttribute(MASTER) User master,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("communityId: " + communityId);
		List<Map<String, Object>> communityRoom = null;
		try {
			communityRoom = this.masterService.findMasterRoom(NumberUtils.toInt(communityId), master.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String communityName = (String) getCommunityValue(communityId, "name");// 小区名
		String deptId = getCommunityValue(communityId, "dept_id") + "";
		String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
		request.setAttribute("address", departmentName + " " + communityName);
		request.setAttribute("rooms", communityRoom);
		return Constant.PATH_MASTER + "roomList";
	}

	@RequestMapping(value = "/{communityId}/{roomId}/roomEdit.htm")
	public String roomEdit(@PathVariable("communityId") String communityId, @PathVariable("roomId") String roomId,
			@ModelAttribute(MASTER) User master, HttpServletRequest request, HttpServletResponse response) {
		String building = request.getParameter("building");
		String unit = request.getParameter("unit");
		String room_num = request.getParameter("room_num");
		String rent_type = request.getParameter("rent_type");
		String room_price = request.getParameter("room_price");
		String deposit = request.getParameter("deposit");

		boolean result = false;// 操作结果

		if (StringUtils.isBlank(rent_type)) {
			// 打开修改页面
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", roomId);
			Map<String, Object> room = null;
			try {
				room = this.masterService.findRoom(condition);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("room", room);
			return Constant.PATH_MASTER + "roomEdit";
		} else if ("0".equals(roomId)) {
			// 新增
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("building", building);
			data.put("unit", unit);
			data.put("room_num", room_num);

			Map<String, Object> existRoom = null;
			try {
				existRoom = this.masterService.findRoom(data);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (null != existRoom && null != existRoom.get("id")) {
				log.error("房间已存在");
				this.alert("房间已存在", request);
			} else {
				data.put("rent_type", rent_type);
				data.put("room_price", room_price);
				data.put("deposit", deposit);
				data.put("community_id", communityId);
				data.put("main_id", master.getUserId());
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("id", roomId);
				try {
					long room_id = this.masterService.saveRoom(data, condition);

					result = room_id > 0L;
					if (result) {
						Map<String, Object> roomAdd = new HashMap<String, Object>();
						roomAdd.put("roomId", room_id);
						roomAdd.put("classId", room_id);
						roomAdd.put("name", room_num);
						Map<String, String> wxAddRoomClass = this.eRentService.wxAddRoomClass(roomAdd);
						if ("1".equals(wxAddRoomClass.get("flag"))) {
							log.info("接口新增房间失败, 删除刚刚新增的房间id: " + room_id);
							this.masterService.deleteRoom((int) room_id, master.getUserId());
							result = false;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!result) {
					log.error("新增房间失败");
					this.alert("新增失败", request);
				}
			}
		} else {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("id", roomId);
			data.put("room_num", room_num);

			Map<String, Object> existRoom = null;
			try {
				existRoom = this.masterService.findRoom(data);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (null != existRoom && !roomId.equals(existRoom.get("id") + "")) {
				log.error("房间已存在");
				this.alert("房间已存在", request);
			} else {
				// 保存修改
				data.clear();
				data.put("room_num", room_num);
				data.put("rent_type", rent_type);
				data.put("room_price", room_price);
				data.put("deposit", deposit);
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("id", roomId);
				try {
					Map<String, Object> roomUpdate = new HashMap<String, Object>();
					roomUpdate.put("roomId", roomId);
					roomUpdate.put("classId", roomId);
					roomUpdate.put("name", room_num);
					Map<String, String> wxUpdRoomClass = this.eRentService.wxUpdRoomClass(roomUpdate);
					if ("0".equals(wxUpdRoomClass.get("flag"))) {
						result = this.masterService.updateRoom(data, condition);
					} else {
						log.error("接口更新房间失败");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!result) {
					log.error("修改房间失败");
					this.alert("修改失败", request);
				}
			}
		}
		return this.redirect(Constant.PATH_MASTER + communityId + "/roomList.htm?result=" + result, request);
	}

	@RequestMapping(value = "/{communityId}/{roomId}/roomDel.json")
	@ResponseBody
	public Map<String, Object> roomDel(@PathVariable("communityId") String communityId,
			@PathVariable("roomId") String roomId, @ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		boolean result = false;
		Map<String, Object> json = new HashMap<String, Object>();

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("id", roomId);

		Map<String, Object> existRoom = null;
		try {
			existRoom = this.masterService.findRoom(data);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (null != existRoom && 1 == (Integer) existRoom.get("is_rent")) {
			log.error("房间已出租，不能删除");
			// this.alert("房间已出租，不能删除", request);
			json.put("msg", "房间已出租，不能删除");
		} else {
			try {
				List<Map<String, Object>> bedList = this.masterService.findBedByClassId(NumberUtils.toInt(roomId));
				if (null != bedList && !bedList.isEmpty()) {
					json.put("msg", "房间下有床位，请先删除所有床位");
				} else {
					Map<String, Object> roomDel = new HashMap<String, Object>();
					roomDel.put("roomId", roomId);
					roomDel.put("classId", roomId);
					Map<String, String> wxAddClassBed = this.eRentService.wxDelRoomClass(roomDel);
					if ("0".equals(wxAddClassBed.get("flag"))) {
						result = this.masterService.deleteRoom(Integer.valueOf(roomId), master.getUserId());
						json.put("msg", "删除房间成功");
					} else {
						log.error("接口删除房间失败");
						json.put("msg", wxAddClassBed.get("msg"));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// return this.redirect(Constant.PATH_MASTER + communityId +
		// "/roomList.htm?result=" + result, request);
		json.put("success", result);
		return json;
	}

	@RequestMapping(value = "/{communityId}/{roomId}/bedList.htm")
	public String bedList(@PathVariable("communityId") String communityId, @PathVariable("roomId") String roomId,
			HttpServletRequest request, HttpServletResponse response) {
		log.debug("roomId: " + roomId);
		List<Map<String, Object>> roomBed = null;
		try {
			roomBed = masterService.findBedByClassId(NumberUtils.toInt(roomId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String communityName = (String) getCommunityValue(communityId, "name");// 小区名
		String deptId = getCommunityValue(communityId, "dept_id") + "";
		String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
		String roomAddress = "";// 房屋名

		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("id", roomId);
		try {
			Map<String, Object> room = this.masterService.findRoom(condition);
			roomAddress = (String) room.get("building") + "栋" + (String) room.get("unit") + "单元"
					+ (String) room.get("room_num") + "房";
		} catch (Exception e) {
			e.printStackTrace();
		}

		request.setAttribute("address", departmentName + " " + communityName + " " + roomAddress);
		request.setAttribute("beds", roomBed);
		return Constant.PATH_MASTER + "bedList";
	}

	@RequestMapping(value = "/{communityId}/{roomId}/{bedId}/bedEdit.htm")
	public String bedEdit(@PathVariable("communityId") String communityId, @PathVariable("roomId") String roomId,
			@PathVariable("bedId") String bedId, @ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		String bed_num = request.getParameter("bed_num");
		String bed_price = request.getParameter("bed_price");
		String deposit = request.getParameter("deposit");

		boolean result = false;// 操作结果

		if (StringUtils.isBlank(deposit)) {
			// 打开修改页面
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", bedId);
			Map<String, Object> bed = null;
			try {
				bed = this.masterService.findBed(condition);
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("bed", bed);

			// 查询地址信息
			String communityName = (String) getCommunityValue(communityId, "name");// 小区名
			String deptId = getCommunityValue(communityId, "dept_id") + "";
			String departmentName = (String) getDepartmentValue(deptId, "name");// 社区名
			String address = "";// 房间地址
			String roomName = "";// 房间名

			Map<String, Object> condition2 = new HashMap<String, Object>();
			condition2.put("id", roomId);
			try {
				Map<String, Object> room = masterService.findRoom(condition2);
				address = departmentName + " " + communityName + " " + (String) room.get("building") + "栋 "
						+ (String) room.get("unit") + "单元";
				roomName = (String) room.get("room_num");
			} catch (Exception e) {
				e.printStackTrace();
			}

			request.setAttribute("address", address);
			request.setAttribute("roomName", roomName);

			return Constant.PATH_MASTER + "bedEdit";
		} else if ("0".equals(bedId)) {
			// 新增
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("room_id", roomId);
			data.put("bed_num", bed_num);

			Map<String, Object> existBed = null;
			try {
				existBed = this.masterService.findBed(data);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (null != existBed && null != existBed.get("id")) {
				log.error("床位已存在");
				this.alert("床位已存在", request);
			} else {
				data.put("bed_price", bed_price);
				data.put("deposit", deposit);
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("id", bedId);
				try {
					long bed_id = this.masterService.saveBed(data, condition);

					result = bed_id > 0L;
					if (result) {
						Map<String, Object> bedAdd = new HashMap<String, Object>();
						bedAdd.put("roomId", roomId);
						bedAdd.put("classId", roomId);
						bedAdd.put("bedId", bed_id);
						bedAdd.put("name", bed_num);
						Map<String, String> wxAddClassBed = this.eRentService.wxAddClassBed(bedAdd);
						if ("1".equals(wxAddClassBed.get("flag"))) {
							log.info("接口新增床位失败, 删除刚刚新增的床位id: " + bed_id);
							this.masterService.deleteBed((int) bed_id, master.getUserId());
							result = false;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!result) {
					log.error("新增床位失败");
					this.alert("新增失败", request);
				}
			}
		} else {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("id", bedId);
			data.put("bed_num", bed_num);

			Map<String, Object> existBed = null;
			try {
				existBed = this.masterService.findBed(data);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (null != existBed && !bedId.equals(existBed.get("id") + "")) {
				log.error("床位已存在");
				this.alert("床位已存在", request);
			} else {
				// 保存修改
				data.put("bed_price", bed_price);
				data.put("deposit", deposit);
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("id", bedId);
				try {
					Map<String, Object> bedUpdate = new HashMap<String, Object>();
					bedUpdate.put("roomId", roomId);
					bedUpdate.put("classId", roomId);
					bedUpdate.put("bedId", bedId);
					bedUpdate.put("name", bed_num);
					Map<String, String> wxUpdClassBed = this.eRentService.wxUpdClassBed(bedUpdate);
					if ("0".equals(wxUpdClassBed.get("flag"))) {
						result = this.masterService.updateBed(data, condition);
					} else {
						log.error("接口更新床位失败");
						this.masterService.deleteBed(NumberUtils.toInt(bedId), master.getUserId());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (!result) {
					log.error("修改床位间失败");
					this.alert("修改失败", request);
				}
			}
		}
		return this.redirect(Constant.PATH_MASTER + communityId + "/" + roomId + "/bedList.htm?result=" + result,
				request);
	}

	@RequestMapping(value = "/{communityId}/{roomId}/{bedId}/bedDel.json")
	@ResponseBody
	public Map<String, Object> bedDel(@PathVariable("communityId") String communityId,
			@PathVariable("roomId") String roomId, @PathVariable("bedId") String bedId,
			@ModelAttribute(MASTER) User master, HttpServletRequest request, HttpServletResponse response) {
		boolean result = false;
		Map<String, Object> json = new HashMap<String, Object>();

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("id", bedId);

		Map<String, Object> existBed = null;
		try {
			existBed = this.masterService.findBed(data);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (null != existBed && 1 == (Integer) existBed.get("is_rent")) {
			log.error("床位已出租，不能删除");
			// this.alert("床位已出租，不能删除", request);
			json.put("msg", "床位已出租，不能删除");
		} else {
			try {
				Map<String, Object> bedDel = new HashMap<String, Object>();
				bedDel.put("roomId", roomId);
				bedDel.put("classId", roomId);
				bedDel.put("bedId", bedId);
				Map<String, String> wxDelClassBed = this.eRentService.wxDelClassBed(bedDel);
				if ("0".equals(wxDelClassBed.get("flag"))) {
					result = this.masterService.deleteBed(Integer.valueOf(bedId), master.getUserId());
					json.put("msg", "删除床位成功");
				} else {
					log.error("接口删除床位失败");
					json.put("msg", wxDelClassBed.get("msg"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// return this.redirect(Constant.PATH_MASTER + communityId + "/" +
		// roomId + "/bedList.htm?result=" + result,
		// request);
		json.put("success", result);
		return json;
	}

	@RequestMapping(value = "/orderList.htm")
	public String orderList(Pager pager, @ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		// log.debug("renterId: " + renterId);
		if (null != master) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("main_id", master.getUserId());

			Pager myOrder = null;
			try {
				myOrder = this.masterService.findMyOrder(map, pager.getPageNo(), pager.getPageSize());
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute(PAGER_MODEL, myOrder);
		}
		return Constant.PATH_MASTER + "orderList";
	}

	@RequestMapping(value = "/{orderId}/confirm.htm")
	@ResponseBody
	public String confirm(@PathVariable String orderId, @ModelAttribute(MASTER) User master,
			HttpServletRequest request, HttpServletResponse response) {
		log.info("用户" + master.getUserId() + " 确认定单" + orderId);
		Boolean success = false;
		if (null != master) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("state", Constant.ORDER_STATE_PAYING);
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", orderId);
			condition.put("main_id", master.getUserId());

			try {
				success = this.masterService.updateMyOrder(data, condition);

				Map<String, Object> order = masterService.findOrder(condition);
				Map<String, Object> renterCondition = new HashMap<String, Object>();
				renterCondition.put("id", order.get("grant_id"));
				User renter = renterService.loadUser(renterCondition);
				smsService.saveSms(null, renter.getUserPhone(), master.getUserName() + "同意了您的订单，请登陆“云i租”进行支付。");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return success.toString();
	}

	@RequestMapping(value = "/{orderId}/cancel.htm")
	@ResponseBody
	public String cancel(@PathVariable String orderId, @ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		log.info("用户" + master.getUserId() + " 取消定单" + orderId);
		Boolean success = false;

		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("id", orderId);
		condition.put("main_id", master.getUserId());

		// 先调接口的解绑房客
		try {
			Map<String, Object> bed = this.masterService.findBed(condition);

			Map<String, Object> bedGrantDel = new HashMap<String, Object>();
			bedGrantDel.put("roomId", bed.get("room_id"));
			bedGrantDel.put("classId", bed.get("room_id"));
			bedGrantDel.put("bedId", bed.get("id"));
			bedGrantDel.put("grantId", bed.get("grant_id"));
			Map<String, String> wxDelBedGrant = this.eRentService.wxDelBedGrant(bedGrantDel);
			if ("1".equals(wxDelBedGrant.get("flag"))) {
				log.error("接口删除房间失败");
				return success.toString();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return success.toString();
		}

		// 再走本地流程
		Map<String, Object> order = null;
		if (null != master) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("state", Constant.ORDER_STATE_CANCEL);

			try {
				success = this.masterService.updateMyOrder(data, condition);
				if (success) {
					order = masterService.findOrder(condition);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (success && null != order) {
			log.info("更新床位状态为“已取消”");
			String bedId = order.get("bed_id") + "";
			// 同时更新床位状态
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("is_rent", Constant.BED_STATE_NORENT);
			data.put("grant_id", null);
			data.put("room_id", order.get("room_id"));
			if (StringUtils.isNotBlank(bedId) && NumberUtils.toInt(bedId) > 0) {
				data.put("id", bedId);
			}
			try {
				renterService.updateBedState(data);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return success.toString();
	}

	@RequestMapping(value = "/mainRoomList.htm")
	public String mainRoomList(@ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("main_id", master.getUserId());
		try {
			List<Map<String, Object>> roomList = this.masterService.mainRoomList(condition);
			request.setAttribute("roomList", roomList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return Constant.PATH_MASTER + "mainRoomList";
	}

	@RequestMapping(value = "/{communityId}/{roomId}/mainRoomGrantList.htm")
	public String mainRoomGrantList(@PathVariable String communityId, @PathVariable String roomId,
			@ModelAttribute(MASTER) User master, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("room_id", roomId);
		try {
			List<Map<String, Object>> renterList = this.masterService.mainRoomGrantList(condition);
			request.setAttribute("renterList", renterList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return Constant.PATH_MASTER + "mainRoomGrantList";
	}

	@RequestMapping(value = "/mainRoomGrantList.json")
	@ResponseBody
	public List<Map<String, Object>> mainRoomGrantList(@ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("main_id", master.getUserId());
		try {
			return this.masterService.mainRoomList(condition);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@RequestMapping(value = "/{communityId}/{roomId}/{grantId}/openGrantUpd.htm")
	public String openGrantUpd(@PathVariable String communityId, @PathVariable String roomId,
			@PathVariable String grantId, @ModelAttribute(MASTER) User master, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("id", grantId);
		try {
			List<Map<String, Object>> renters = this.renterService.findRenter(data);
			if (null != renters && !renters.isEmpty()) {
				request.setAttribute("renter", renters.get(0));
				data.put("id", renters.get(0).get("rentid"));
				Map<String, Object> grantRoom = this.masterService.grantRoom(data);
				request.setAttribute("room", grantRoom);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Constant.PATH_MASTER + "mainRoomGrantEdit";
	}

	@RequestMapping(value = "/{communityId}/{grantId}/grantUpd.htm")
	public String grantUpd(@PathVariable String communityId, @PathVariable String grantId,
			@ModelAttribute(MASTER) User master, HttpServletRequest request, HttpServletResponse response) {
		String roomId = request.getParameter("roomId");
		String endDate = request.getParameter("endDate");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("roomId", roomId);
		data.put("grantId", grantId);
		data.put("endDate", endDate);
		try {
			Map<String, String> wxUpdGrant = this.eRentService.wxUpdGrant(data);
			this.alert(wxUpdGrant.get("flag"), request);
			if ("1".equals(wxUpdGrant.get("flag"))) {
				log.error("接口修改人员失败");
			} else {
				this.renterService.updGrant(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.redirect(Constant.PATH_MASTER + communityId + "/" + roomId + "/" + grantId + "/openGrantUpd.htm",
				request);
	}

	@RequestMapping(value = "/grantDel.htm")
	public String grantDel(@ModelAttribute(MASTER) User master, HttpServletRequest request, HttpServletResponse response) {
		String renterId = request.getParameter("renterId");
		String communityId = request.getParameter("communityId");
		String roomId = request.getParameter("roomId");

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("roomId", roomId);
		data.put("grantId", renterId);
		try {
			Map<String, String> wxDelGrant = this.eRentService.wxDelGrant(data);
			this.alert(wxDelGrant.get("msg"), request);
			if ("1".equals(wxDelGrant.get("flag"))) {
				log.error("接口删除人员失败");
			} else {
				this.renterService.clearUserRoom(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.redirect(Constant.PATH_MASTER + communityId + "/" + roomId + "/mainRoomGrantList.htm", request);
	}

	@RequestMapping(value = "/getOpenidByCode.htm")
	@ResponseBody
	protected String getOpenidByCode(@RequestParam(value = "openacc") String openacc,
			@RequestParam(value = "code") String code) {
		return super.getOpenidByCode(openacc, code);
	}

}
